package com.android.base.base;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;

import com.android.base.BaseLazyFragment;
import com.android.base.BasePresenter;
import com.android.base.BaseViewI;
import com.android.base.MyApplication;
import com.android.base.R;
import com.android.base.VersionEvent;
import com.android.base.bean.UserInfoBean;
import com.android.base.http.ResultTag;
import com.android.base.utils.AppConfig;
import com.android.base.utils.GeneralUtil;
import com.android.base.utils.MLog;
import com.android.base.utils.ToastShow;
import com.android.base.widget.dialog.LoadingDialog;
import com.android.base.widget.loading.VaryViewHelperController;

import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * 懒加载Fragment 只有创建并显示的时候才会调用onCreateViewLazy方法
 * <p>
 * 懒加载的原理onCreateView的时候Fragment有可能没有显示出来。
     * 但是调用到setUserVisibleHint(boolean isVisibleToUser),isVisibleToUser =
 * true的时候就说明有显示出来
 * 但是要考虑onCreateView和setUserVisibleHint的先后问题所以才有了下面的代码
 * <p>
 * 注意：
 * 《1》原先的Fragment的回调方法名字后面要加个Lazy，比如Fragment的onCreateView方法， 就写成onCreateViewLazy <br>
 * 《2》使用该LazyFragment会导致多一层布局深度
 *
 * @author LuckyJayce
 */
public abstract class LazyFragment<T extends BasePresenter,V> extends BaseLazyFragment implements BaseViewI<V> {
    private boolean isInit = false;//真正要显示的View是否已经被初始化（正常加载）
    private Bundle savedInstanceState;
    public static final String INTENT_BOOLEAN_LAZYLOAD = "intent_boolean_lazyLoad";
    private boolean isLazyLoad = true;
    private FrameLayout layout;
    private boolean isStart = false;//是否处于可见状态，in the screen
    protected T mPresenter;

    protected VaryViewHelperController mVaryViewHelperController;
    private LoadingDialog loadDialogView;

    @Override
    protected final void onCreateView(Bundle savedInstanceState) {
        MLog.i("TAG", "onCreateView() : " + "getUserVisibleHint():" + getUserVisibleHint());
        super.onCreateView(savedInstanceState);
        Bundle bundle = getArguments();

        if (bundle != null) {
            isLazyLoad = bundle.getBoolean(INTENT_BOOLEAN_LAZYLOAD, isLazyLoad);
        }
        //判断是否懒加载
        if (isLazyLoad) {
            //一旦isVisibleToUser==true即可对真正需要的显示内容进行加载
            if (getUserVisibleHint() && !isInit) {
                this.savedInstanceState = savedInstanceState;
                onCreateViewLazy(savedInstanceState);
                isInit = true;
            } else {
                //进行懒加载
                layout = new FrameLayout(getActivity());
                layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.lazy_progress_layout, null);
                layout.addView(view);
                super.setContentView(layout);
                initLazyLoadding();
            }
        } else {
            //不需要懒加载，开门江山，调用onCreateViewLazy正常加载显示内容即可
            onCreateViewLazy(savedInstanceState);
            isInit = true;
        }





    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("TAG", "setUserVisibleHint() called with: " + "isVisibleToUser = [" + isVisibleToUser + "]");
        //一旦isVisibleToUser==true即可进行对真正需要的显示内容的加载

        //可见，但还没被初始化
        if (isVisibleToUser && !isInit && getContentView() != null) {
            onCreateViewLazy(savedInstanceState);
            isInit = true;
            onResumeLazy();
        }
        //已经被初始化（正常加载）过了
        if (isInit && getContentView() != null) {
            if (isVisibleToUser) {
                isStart = true;
                onFragmentStartLazy();
            } else {
                isStart = false;
                onFragmentStopLazy();
            }
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        //判断若isLazyLoad==true,移除所有lazy view，加载真正要显示的view
        if (isLazyLoad && getContentView() != null && getContentView().getParent() != null) {
            layout.removeAllViews();
            View view = inflater.inflate(layoutResID, layout, false);
            layout.addView(view);
        }
        //否则，开门见山，直接加载
        else {
            super.setContentView(layoutResID);
        }


    }




    @Override
    public void setContentView(View view) {
        //判断若isLazyLoad==true,移除所有lazy view，加载真正要显示的view
        if (isLazyLoad && getContentView() != null && getContentView().getParent() != null) {
            layout.removeAllViews();
            layout.addView(view);
        }
        //否则，开门见山，直接加载
        else {
            super.setContentView(view);
        }
    }

    @Deprecated
    @Override
    public final void onStart() {
        Log.d("TAG", "onStart() : " + "getUserVisibleHint():" + getUserVisibleHint());
        super.onStart();
        if (isInit && !isStart && getUserVisibleHint()) {
            isStart = true;
            onFragmentStartLazy();
        }
    }

    @Deprecated
    @Override
    public final void onStop() {
        super.onStop();
        if (isInit && isStart && getUserVisibleHint()) {
            isStart = false;
            onFragmentStopLazy();
        }
    }

    //当Fragment被滑到可见的位置时，调用
    protected void onFragmentStartLazy() {
    }

    //当Fragment被滑到不可见的位置，offScreen时，调用
    protected void onFragmentStopLazy() {
    }

    protected void onCreateViewLazy(Bundle savedInstanceState) {

    }

    protected void onResumeLazy() {
    }

    protected void onPauseLazy() {

    }

    protected void onDestroyViewLazy() {
        ButterKnife.unbind(this);
        if(mPresenter!=null){
            mPresenter.unsubcrible();
        }
        if(loadDialogView!=null){
            loadDialogView.dismiss();
        }
//        RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity());
//        refWatcher.watch(this);
    }

    @Override
    @Deprecated
    public final void onResume() {
        super.onResume();
        if (isInit) {
            onResumeLazy();
        }
    }

    @Override
    @Deprecated
    public final void onPause() {
        super.onPause();
        if (isInit) {
            onPauseLazy();
        }
    }

    @Override
    @Deprecated
    public final void onDestroyView() {
        super.onDestroyView();
        if (isInit) {
            onDestroyViewLazy();
        }
        isInit = false;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }




    public T getPresenter() {
        return null;
    }
    /**
     *
     *
     * 具体在哪个部位显示加载中，加载失败，网络异常等
     * */
    protected View getLoadingTargetView() {
        return null;
    }

    /**
     * 显示加载弹框
     * */
    @Override
    public void showProgress() {
        if (loadDialogView == null) {
            loadDialogView = LoadingDialog.createDialog(getActivity());

        }

        loadDialogView.show();
    }

    /**
     * 隐藏加载弹框
     * */
    @Override
    public void hideProgress() {
        if (loadDialogView != null) {

            loadDialogView.dismiss();

        }
    }

    /**
     * 加载失败后重新加载
     * */
    @Override
    public void onReload() {

    }



    @Override
    public void showDataError(String errorMessage, int tag) {
        hideProgress();

        if (!GeneralUtil.isEmpty(errorMessage)) {
            if(tag != ResultTag.VERSION) {
                ToastShow.getInstance(getActivity()).toastShow(errorMessage, ToastShow.ERROR_FLAG);
            }
        }


        if (tag == ResultTag.LOGINSTTUS_ERROR) {
            AppConfig.getInstance(getActivity()).setUserInfo(new UserInfoBean(), false);
            MyApplication.getInstance().exitNoMain();
//            startActivity(new Intent(getActivity(), LoginActivity.class));
        }


        if (tag == ResultTag.VERSION) {
            EventBus.getDefault().post(new VersionEvent());
            MyApplication.getInstance().exitNoMain();
            return;
        }
    }

    @Override
    public void showDataSuccess(V datas) {
        hideProgress();
    }

    @Override
    public void showLoadingView() {
        if (mVaryViewHelperController == null) {
            throw new IllegalStateException("no ViewHelperController");
        }
        mVaryViewHelperController.showLoading();
    }

    @Override
    public void showNetErrorView() {
        if (mVaryViewHelperController == null) {
            throw new IllegalStateException("no ViewHelperController");
        }
        mVaryViewHelperController.showNetworkError(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onReload();
            }
        });
    }

    @Override
    public void showLoadErrorView(String msg, int resoulce) {

        if (mVaryViewHelperController == null) {
            throw new IllegalStateException("no ViewHelperController");
        }

        mVaryViewHelperController.showLoadError(msg, resoulce, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onReload();
            }
        });

    }

    @Override
    public void showEmptyView(String msg,int resoulce) {
        if (mVaryViewHelperController == null) {
            throw new IllegalStateException("no ViewHelperController");
        }
        mVaryViewHelperController.showEmpty(msg,resoulce);
    }

    @Override
    public void showContent() {
        if (mVaryViewHelperController == null) {
            throw new IllegalStateException("no ViewHelperController");
        }
        mVaryViewHelperController.restore();
    }


    public void initLazyLoadding(){
        if (null != getLoadingTargetView()) {
            mVaryViewHelperController = new VaryViewHelperController(getLoadingTargetView());
        }
    }

    @Override
    public void onNetworkError() {

    }
}